unique_ptr and nullptr

Hi,

I'm playing with unique_ptr right now and I'm not sure of the behavior of the code below. The show() method show a browse dialog for a file selection and returns a unique_ptr but if the user cancel it returns nullptr.
Even if I return a nullptr I can call the get() method of unique_ptr. Forgive my "maybe" stupid question but what is happening to be possible. Something about objects still puzzles me.

1
2
3
BrowseFileSystem bfs;
std::unique_ptr<WCHAR[]> path = bfs.show();
MessageBoxW(0, path.get() , 0, 0);


http://www.cplusplus.com/reference/memory/unique_ptr/unique_ptr/

You call the constructor on line 2 and if the user did cancel, it is effectively the "from nullptr" constructor.

The 'path' object exists, but does not "own" any wchar array.

1
2
3
BrowseFileSystem bfs;
std::unique_ptr<WCHAR[]> path = bfs.show();
if ( path ) MessageBoxW(0, path.get() , 0, 0);

http://www.cplusplus.com/reference/memory/unique_ptr/operator%20bool/
> Even if I return a nullptr I can call the get() method of unique_ptr

Yes. std::unique_ptr<>::get() returns nullptr if the std::unique_ptr<> is null (it does not own an object).

And MessageBoxW() accepts a nullptr for the second parameter (the message displayed is an empty string).

Note: I've no idea about the type BrowseFileSystem.

Ok I get it now. I thought the unique_ptr did not exist when I passed a nullptr. My mistake. Thanks.

Note: I've no idea about the type BrowseFileSystem


I hope so!... It's a class I made. I'm coding all kind of small stuff like this to get used to the concept of OO and C++.
Give me few weeks and maybe I'll be using std::wstring instead of the old wchar array or std::vector instead of c-style array. It's not easy to change an old way of thinking :-)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class BrowseFileSystem
{
public:

	typedef std::unique_ptr<WCHAR[]> PWCHAR_UNIQUE;
	enum DlgType{ Folders, Files, All };

	PWCHAR_UNIQUE show(
		DlgType dialog_type,
		HWND owner,
		LPCWSTR title_bar,
		LPCWSTR banner,
		LPCWSTR initial_path,
		INT root_view,
		BOOL new_folder_button);

private:

	typedef struct BFFCALLBACKDATA {
		LPCWSTR title_bar_text;
		LPCWSTR initial_path;
		BOOL is_file_dialog;
	} *PBFFCALLBACKDATA;

	static int CALLBACK BrowseCallbackProc(
		HWND hwnd,
		UINT msg,
		LPARAM lparam,
		LPARAM data);

};
Topic archived. No new replies allowed.