C++ string 초기화 방법 질문입니다.

slal1207의 이미지

C++ string 초기화 문제 풀던중에 이런문제가 나왔는데 인터넷을 아무리 찾아도 답이 안나오네요ㅠㅠ
string some_str = "asdf"
string some_str("asdf")
두가지 선언 방법중에 더 좋은걸 찾고 그 이유를 쓰라는데 둘이 같은 방법 아닌가요?

세벌의 이미지

C++ 공식 레퍼런스 찾아봤습니다.

http://www.cplusplus.com/reference/string/string/string/

std::string s0 ("Initial string");
두번째 방법이 좋은 것 같습니다. 까닭은 공식 레퍼런스에 나오니.

https://www.linuxtopia.org/online_books/programming_books/c++_practical_programming/c++_practical_programming_057.html 도 봤습니다.

두 가지 다 되는 것 같네요. 어느 게 좋은지는 모르겠네요...

shint의 이미지

https://ideone.com/iqci2Q
http://www.cplusplus.com/reference/string/string/operator=/

#include <iostream>
 
using namespace std;
 
class CString
{
public:
    CString(){}
    CString(const string& str)
    {
    	m_str = str;
    	cout << "생성자:" << m_str << endl;
    }
    ~CString(){}
 
	string m_str;
 
    string& operator= (const string& str)
    {
    	m_str = str;
    	cout << "operator=" << m_str << endl;
    }
};
 
int main()
{
	CString str("test");
	str = "abc";
    return 0;
}
 
//
생성자:test
operator=abc

----------------------------------------------------------------------------
젊음'은 모든것을 가능하게 만든다.

매일 1억명이 사용하는 프로그램을 함께 만들어보고 싶습니다.
정규 근로 시간을 지키는. 야근 없는 회사와 거래합니다.

각 분야별. 좋은 책'이나 사이트' 블로그' 링크 소개 받습니다. shintx@naver.com

익명 사용자의 이미지

쉬운 답변: 똑같아요

어려운 답변: 전자는 클래스 타입을 다른 타입으로 초기화하는 copy-initialization이고 후자는 클래스 타입에 대한 direct-initialization이라서 후자는 직접 생성자를 호출하여 초기화하고 전자는 prvalue인 string 임시 객체를 생성한 다음에 그걸로 direct-initialization을 하도록 되어 있지만 보통 컴파일러가 copy elision 처리해버리기 때문에 결국 양쪽 모두 string literal로 생성자 호출하여 some_str를 초기화하게 됩니다.

대체로 이건 초보자에게 주는 함정 퀴즈이거나 중급자 이상에게 C++ 문법 및 의미론, 컴파일러 구현을 얼마나 잘 이해하고 있는지를 묻는 깊이 있는 문제인데, 각각 쉬운 답변과 어려운 답변으로 답하면 될 겁니다.

예외적으로 가끔 정답지에 "다르다"라고 적혀 있는 경우가 있는데 그 경우는 문제를 낸 쪽에게 문제가 있다고 봄.

익명 사용자의 이미지

물론 위에서 같다고 한 건 생성되는 object code를 봤을 때 같다는 거고, 코딩 스타일 측면에서 다르다고 주장한다면 인정.

문제는 스타일이란 게 사람마다 다르다는 건데, 대체로 파라미터 한 개를 받아 객체를 생성할 때 생성자가 하는 일이 trivial하면 (단순 변환이라던가) 전자를, non-trivial하면 후자를 선호하며, 남의 코드를 읽을 때도 그런 식으로 해석하는 경우가 많습니다.

다만 string literal로부터 string을 만드는 것이 trivial한 일인지 아닌지 판단하는 건 non-trivial한 일이지요.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.