Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string s() strange behaviour [duplicate]

Tags:

c++

string

I have found something wierd which I don't understand.

std::string a();

When printed out it returns 1. I have no idea where it came from. I thought a() is a constructor without arguments, but it looks like it isn't.

Where can I find information about this? and what is this?

And when trying to do std::string b(a); compiler shouts:

error: no matching function for call to ‘std::basic_string<char>::basic_string(std::string (&)())’

Explanation would be appreciated.

like image 984
jaor Avatar asked May 28 '13 10:05

jaor


2 Answers

This is a function declaration, not a string instantiation:

std::string a();

It declares a function called a, with no parameters, and returning an std:string. These are instantiations:

std::string a;   // C++03 and C++11
std::string b{}; // C++11 syntax
like image 50
juanchopanza Avatar answered Sep 19 '22 15:09

juanchopanza


std::string a();

Declares a function with no arguments and std::string as return type. When you trying to print it, you print address, which is evaluating to true.

warning: the address of ‘std::string a()’ will always evaluate as ‘true’ [-Waddress]

like image 42
awesoon Avatar answered Sep 22 '22 15:09

awesoon