开发者

pass c_str return value of temporary object to printf

Is the following piece of code valid?

class A { string m_name;

public:

string getName() { return m_name; }

}

.....

printf("%s", object.getName().c_str())

.....开发者_StackOverflow社区.

where object.getName() returns a temporary string object.


The temporary string will persist for until printf() completes so yes, it is safe and legal.


Looks valid to me, assuming get name will return a standard string object.


Provided object.getName() returns by value, or by reference to something that remains valid:

yes


Your code as I'm writing this:

class A { string m_name;
public:
string getName() { return m_name; }
}

.....
printf("%s", object.getName().c_str())
......

You ask, is the code valid?

No, the code is not valid, because

  • there is a missing semicolon at the end of the class definition, and
  • “....” is invalid as C++ code, and
  • there is a missing semicolon at the end of the printf statement.

In short, the code will not compile.

Please, in the future, post code that can be compiled, so that people who want to help you can try it out for real as-is (and be sure that it is the code that you're asking about).


Now regarding style issues.

string getName() { return m_name; }

The lack of const is ungood style.

You should make the member function const, so that it then can be called on a const object.

Also, the get prefix is stylistically an abomination, in C++. Would you write getSin? The get prefix has a purpose in Java, but in C++ it is just visual noise and textual verbosity, i.e. it is like playing with a beach ball in a fine restaurant: what was nice on the beach (Java) is not so good in the restaurant (C++).

printf("%s", object.getName().c_str());

The .c_str() call is stylistically OK, because most C++ programmers do this and know that it is OK. If if it was a rarely used construction, then it could be bad style, because then other people might waste time checking whether it is formally OK. It's formally OK because the temporary lasts until the end of the full-expression.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜